<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\controller\WXBizDataCrypt;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\Activity;
use app\common\model\Address;
use app\common\model\Application;
use app\common\model\AwardCeremony;
use app\common\model\Category;
use app\common\model\CountNumber;
use app\common\model\Goods;
use app\common\model\Group;
use app\common\model\SignUp;
use fast\Random;
use think\Config;
use think\Db;
use think\Exception;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['awardWinningProduct', 'login', 'simulateLogin', 'mobilelogin', 'register', 'getCityGroup', 'resetpwd', 'changeemail', 'changemobile', 'third', 'weChatAppLogin', 'bindMobile', 'getGoodsDetail'];
    protected $noNeedRight = '*';
    protected $page = 1;
    protected $pageSize = 10;

    public function _initialize()
    {
        parent::_initialize();
        $this->page = $this->request->param('page/d', 1);
        $this->pageSize = $this->request->param('pageSize/d', 10);

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="account", type="string", required=true, description="账号")
     * @ApiParams (name="password", type="string", required=true, description="密码")
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @ApiParams (name="username", type="string", required=true, description="用户名")
     * @ApiParams (name="password", type="string", required=true, description="密码")
     * @ApiParams (name="email", type="string", required=true, description="邮箱")
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="code", type="string", required=true, description="验证码")
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 获取我加入的组别
     * */
    public function getMyJoinGroup()
    {
        $rows = \app\common\model\User::get(['id' => $this->auth->id ?? 0]);
        if (!$rows) {
            $this->success('success', ['group_name' => '']);
        }
        $groupName['group_name'] = Group::where(['id' => $rows['city_group_id']])->value('group_name');
        $this->success('success', $groupName);
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @ApiParams (name="avatar", type="string", required=true, description="头像地址")
     * @ApiParams (name="username", type="string", required=true, description="用户名")
     * @ApiParams (name="nickname", type="string", required=true, description="昵称")
     * @ApiParams (name="bio", type="string", required=true, description="个人简介")
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @ApiParams (name="email", type="string", required=true, description="邮箱")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="platform", type="string", required=true, description="平台名称")
     * @ApiParams (name="code", type="string", required=true, description="Code码")
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo' => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="newpassword", type="string", required=true, description="新密码")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }


    /**
     * 模拟登录
     *
     * @throws
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="newpassword", type="string", required=true, description="新密码")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function simulateLogin()
    {
        $params = $this->request->get();
        if (empty($params['user_id'])) {
            $this->error('缺少用户ID');
        }
        //模拟一次登录
        $this->auth->direct($params['user_id'] ?? 0);
        $data = ['userinfo' => $this->auth->getUserinfo()];
        $this->success(__('Logged in successful'), $data);
    }

    /**
     * 小程序登录
     *
     * @throws
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="newpassword", type="string", required=true, description="新密码")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function weChatAppLogin()
    {
        try {
            if (!$this->request->isPost()) {
                throw new Exception('请求方式请切换为POST');
            }
            $params = $this->request->post();
            $validate = $this->validate($params, 'app\\api\\validate\\User.userWxAppletsLogin');
            if ($validate !== true) {
                throw new Exception($validate);
            }
            // 获取小程序登录
            $url = 'https://api.weixin.qq.com/sns/jscode2session';
            $requestParam = [
                'appid' => config('site.appKey'),
                'secret' => config('site.appSecretKey'),
                'js_code' => $params['js_code'],
                'grant_type' => 'authorization_code'
            ];
            $requestResult = http_query($url, 'get', $requestParam);
            if (!empty($requestResult['errcode'])) {
                throw new Exception('小程序授权错误，【code：' . $requestResult['errcode'] . '】，【描述：' . $requestResult['errmsg'] . '】');
            }
            // 解析微信密文数据，得到用户信息
            $pc = new WXBizDataCrypt(config('site.appKey'), $requestResult['session_key']);
            $errCode = $pc->decryptData($params['encryptedData'], $params['iv'], $data);
            if ($errCode != 0) {
                throw new Exception('小程序授权异常');
            }
            $user_id = (new \app\common\model\User)->login($data);
            if ($ret = $this->auth->direct($user_id)) {
                $data = ['userinfo' => $this->auth->getUserinfo()];
                $this->success(__('Logged in successful'), $data);
            } else {
                $this->error($this->auth->getError());
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 绑定手机号
     * */
    public function bindMobile()
    {
        try {
            if (!$this->request->isPost()) {
                throw new Exception('请求方式请切换为POST');
            }
            $params = $this->request->post();
            $validate = $this->validate($params, 'app\\api\\validate\\User.bindMobile');
            if ($validate !== true) {
                throw new Exception($validate);
            }
            $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $this->getAccessToken()['access_token'];
            $requestParam = json_encode(['code' => $params['code']]);
            $request = http_query($url, 'post', $requestParam);
            if (!empty($request['errcode'])) {
                throw new Exception('小程序授权错误，【code：' . $request['errcode'] . '】，【描述：' . $request['errmsg'] . '】');
            }
            $user_id = (new \app\common\model\User)->bindMobile(array_merge($request['phone_info'], ['openid' => $params['openid']]));
            if ($ret = $this->auth->direct($user_id)) {
                $data = ['userinfo' => $this->auth->getUserinfo()];
                $this->success(__('Logged in successful'), $data);
            } else {
                $this->error($this->auth->getError());
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * @throws Exception
     * */
    protected function getAccessToken()
    {
        $request = http_query('https://api.weixin.qq.com/cgi-bin/token', 'get', [
            'grant_type' => 'client_credential',
            'appid' => config('site.appKey'),
            'secret' => config('site.appSecretKey'),
        ]);
        if (!empty($request['errcode'])) {
            throw new Exception('小程序授权错误，【code：' . $request['errcode'] . '】，【描述：' . $request['errmsg'] . '】');
        }
        return $request;
    }

    /**
     * 用户活动参与打卡
     * */
    public function userApplication()
    {
        $date = date('Y-m-d H:i:s');
        try {
            if (!$this->request->isPost()) {
                throw new Exception('请求方式请切换为POST');
            }
            $params = $this->request->post();
            if (empty($params['activity_id'])) {
                throw new Exception('缺少活动ID');
            }
            if (empty($params['number'])) {
                throw new Exception('缺少打卡次数');
            }
            // todo 判断用户是否已经参与活动
            if (!Application::instance()->where(['user_id' => $this->auth->id ?? 0, 'activity_id' => $params['activity_id']])->find()) {
                throw new Exception('请先参与活动报名');
            }
            if (!$activity = Activity::instance()->get(['id' => $params['activity_id'], 'status' => 1])) {
                throw new Exception('活动不存在');
            }
            // 判断打卡时间是否为空，不为空则按照打卡时间进行打卡
            if (!empty($activity['sign_start_date']) && !empty($activity['sign_end_date'])) {
                if ($activity['sign_start_date'] > date('Y-m-d H:i:s')) {
                    throw new Exception('打卡时间尚未开始');
                }

                if ($activity['sign_end_date'] < date('Y-m-d H:i:s')) {
                    throw new Exception('打卡时间已经结束');
                }
            }
            if ($activity['endtime'] <= $date) {
                throw new Exception('活动已结束');
            }
            // todo 判断是否加入组
            if (!\app\common\model\User::where(['id' => $this->auth->id ?? 0])->value('city_group_id')) {
                throw new Exception('请先加入分组后报名');
            }
            // todo 避免不在该活动组中人成员组进行报名
            $group_id = array_filter(explode(',', $activity['group_id']));
            if ($group_id) {
                $group_id = array_unique($group_id);
                $group = Group::instance()->all(['id' => ['in', $group_id]]);
                $groupName = empty($group) ? '' : implode('|', array_unique(array_column($group, 'group_name')));
                if (!in_array($this->auth->city_group_id, $group_id)) {
                    throw new Exception('本活动只允许组别为【' . $groupName . '】的相关组别参与打卡');
                }
            }

            $signUp = SignUp::instance()
                ->whereTime('createtime', 'today')
                ->where(['activity_id' => $params['activity_id'], 'user_id' => $this->auth->id ?? 0])
                ->find();

            if ($signUp && ($signUp['save_number'] >= $activity['punch_count_number'])) {
                throw new Exception('今日打卡修改次数已用尽');
            }
            $this->success('success', SignUp::instance()->userApplication($activity['id'], $this->auth->id ?? 0, $params['number']));
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 用户活动领奖
     * */
    public function userActivityAward()
    {
        try {
            if (!$this->request->isPost()) {
                throw new Exception('请求方式请切换为POST');
            }
            $params = $this->request->post();
            if (!empty($params['content'])) {
                $params['content'] = htmlspecialchars_decode($params['content']);
            }
            /*if (empty($params['type'])) {
                throw new Exception('缺少商品类型');
            }*/
            if (empty($params['activity_id'])) {
                throw new Exception('缺少活动ID');
            }
            if (empty($params['goods_id'])) {
                throw new Exception('缺少商品ID');
            }
            if (!$activity = Activity::instance()->get(['id' => $params['activity_id'], 'status' => 1])) {
                throw new Exception('活动不存在');
            }
            // todo 查询领取的商品类型
            if (!$goods = Goods::instance()->where(['id' => $params['goods_id']])->find()) {
                throw new Exception('商品不存在');
            }
            if ($goods['method_init'] == 2) {
                if ($activity['startdate'] > date('Y-m-d H:i:s')) {
                    throw new Exception('活动尚未开始');
                }
                if ($activity['endtime'] >= date('Y-m-d H:i:s')) {
                    throw new Exception('活动尚未结束');
                }
            }
            if ($goods['type'] == 1) {
                /*if (empty($params['cate_id'])) {
                    throw new Exception('缺少虚拟商品类型id');
                }*/
                if (empty($params['content'])) {
                    throw new Exception('缺少祈福内容');
                }
                if ($address = Address::instance()->where(['user_id' => $this->auth->id ?? 0])->find()) {
                    $params['address_id'] = $address['id'];
                }
                if (!$address) {
                    $this->error('请点击"我的"右上角设置按钮中进行收货地址填写后领奖');
                }
            } else {
                if (empty($params['address_id'])) {
                    throw new Exception('请点击"我的"右上角设置按钮中进行收货地址填写后领奖');
                }
                if (!$address = Address::instance()->where(['id' => $params['address_id']])->find()) {
                    throw new Exception('地址不存在');
                }
            }
            $application = Application::instance()->where(['activity_id' => $params['activity_id'], 'user_id' => $this->auth->id ?? 0])->find();
            if (!$application) {
                throw new Exception('请先报名');
            }
            // 判断物品的领取方式
            if ($goods['method'] == 2) { // 参与报名后按打卡次数领取
                $signUpNumber = SignUp::instance()
                    // ->whereTime('createtime', 'today')
                    ->where(['activity_id' => $params['activity_id'], 'user_id' => $this->auth->id ?? 0])
                    ->sum('number');
                if (!$signUpNumber) {
                    throw new Exception('请先参与打卡');
                }
                // todo 检测商品是否可以叠加领取
                if ($goods['is_superposition'] == 1) { // todo 不叠加
                    if (!empty($goods['punch_number_min']) && !empty($goods['punch_number_max'])) {
                        if ($signUpNumber >= $goods['punch_number_min'] && $signUpNumber <= $goods['punch_number_max']) {
                            // todo 判断该用户是否领取过该活动下其他的商品
                            if (AwardCeremony::instance()->where(['activity_id' => $activity['id'], 'user_id' => $this->auth->id ?? 0, 'is_superposition' => 1])->find()) {
                                throw new Exception('您已领取过该活动下的其他不叠加商品');
                            }
                        }
                    }
                }
                if (!empty($goods['punch_number_min']) && !empty($goods['punch_number_max'])) {
                    if ($signUpNumber < $goods['punch_number_min'] || $signUpNumber > $goods['punch_number_max']) {
                        throw new Exception('未满足商品打卡区间' . $goods['punch_number_min'] . '-' . $goods['punch_number_max'] . '次的领取要求');
                    }
                }
                // todo 判断商品设置的全国排名区间，用户是否满足在该区间内
                if (!empty($goods['ranking_range_min']) && !empty($goods['ranking_range_max'])) {
                    $myRanking = collection(SignUp::instance()
                        ->alias('t1')
                        ->field('t1.user_id, sum(t1.number) as number, t2.city_group_id, t3.group_name')
                        ->join('user t2', 't1.user_id = t2.id', 'LEFT')
                        ->join('group t3', 't2.city_group_id = t3.id', 'LEFT')
                        ->where(['t1.activity_id' => $activity['id']])
                        ->order('number desc, t1.createtime asc')
                        ->group('t1.user_id')
                        ->select())
                        ->toArray();
                    $nationwideRanking = 0;
                    foreach ($myRanking as $key_ => $value_) {
                        $user_id = $this->auth->id ?? 0;
                        if ($value_['user_id'] == $user_id) {
                            $nationwideRanking = ($key_ + 1);
                        }
                    }
                    if ($nationwideRanking < $goods['ranking_range_min'] || $nationwideRanking > $goods['ranking_range_max']) {
                        throw new Exception('您的排名不在' . $goods['ranking_range_min'] . '~' . $goods['ranking_range_max'] . '的全国排名领取区间内');
                    }
                }
            }

            if ($goods['method'] == 3) { // 参与报名后领取
                if ($goods['is_superposition'] == 1) { // todo 不叠加
                    // todo 判断该用户是否领取过该活动下其他的商品
                    $findAwardCeremony = AwardCeremony::instance()->where(['activity_id' => $activity['id'], 'user_id' => $this->auth->id ?? 0, 'is_superposition' => 1])->find();
                    if ($findAwardCeremony) {
                        throw new Exception('您已领取过该活动下的其他不叠加商品');
                    }
                }
            }
            $params['is_superposition'] = $goods['is_superposition'];
            $response = AwardCeremony::instance()->add($params, $this->auth->id ?? 0);
            $this->success('success', $response);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 添加收货地址
     * */
    public function addAddress()
    {
        try {
            $params = $this->request->post();
            if (empty($params['nickname'])) {
                throw new Exception('缺少用户名称');
            }

            if (empty($params['tel'])) {
                throw new Exception('缺少联系方式');
            }

            if (empty($params['address'])) {
                throw new Exception('缺少收货地址');
            }

            $response = Address::instance()->add($params, $this->auth->id ?? 0);
            $this->success('success', $response);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取收货地址
     * */
    public function getAddress()
    {
        try {
            $list = Address::instance()
                ->field('id, tel, nickname, address, province, city, distinguish')
                ->where(['user_id' => $this->auth->id ?? 0, 'status' => 1])
                ->order('createtime desc')
                ->paginate($this->pageSize, false, ['page' => $this->page]);
            $this->success('success', ['totalPage' => $list->lastPage(), 'list' => $list->items()]);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 编辑收货地址
     * */
    public function editAddress()
    {
        try {
            $params = $this->request->post();
            if (empty($params['id'])) {
                throw new Exception('缺少地址主键ID');
            }

            if (empty($params['nickname'])) {
                throw new Exception('缺少用户名称');
            }

            if (empty($params['tel'])) {
                throw new Exception('缺少联系方式');
            }

            if (empty($params['address'])) {
                throw new Exception('缺少收货地址');
            }
            $response = Address::instance()->editAddress($params, $this->auth->id ?? 0);
            $this->success('success', $response);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 删除收货地址
     * */
    public function delAddress()
    {
        try {
            $params = $this->request->post();
            if (empty($params['id'])) {
                throw new Exception('缺少地址主键ID');
            }
            $response = Address::instance()->delAddress($params);
            $this->success('success', $response);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取领取商品的详情
     * @throws
     * */
    public function getGoodsDetail()
    {
        try {
            $params = $this->request->get();
            if (empty($params['goods_id'])) {
                throw new Exception('缺少商品ID');
            }
            $condition['id'] = $params['goods_id'];
            $condition['status'] = 1;
            if (!$rows = Goods::instance()->field('id, goods_name, goods_images, type, method, cate_ids')->where($condition)->find()) {
                throw new Exception('未找到该商品');
            }
            if ($rows['type'] == 1) { // 虚拟产品分类
                $category = collection(Category::field('id, name, type, flag')->where(['id' => ['in', $rows['cate_ids']]])->select())->toArray();
                $rows['cateList'] = $category;
            }
            $this->success('success', $rows);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取我参与的活动
     * @throws
     * */
    public function participateInActivities()
    {
        try {
            $list = SignUp::instance()
                ->alias('t1')
                ->field('t1.activity_id as id, t1.user_id, t2.title, t2.image, t2.startdate, t2.endtime')
                ->join('activity t2', 't1.activity_id = t2.id', 'RIGHT')
                ->where(['user_id' => $this->auth->id ?? 0])
                ->group('activity_id')
                ->paginate($this->pageSize, false, ['page' => $this->page])->each(function (&$value) {
                    $value['image'] = !empty($value['image']) ? explode(',', $value['image']) : [];
                });
            $this->success('success', ['totalPage' => $list->lastPage(), 'list' => $list->items()]);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取可领奖的产品
     * @throws
     * */
    public function awardWinningProduct()
    {
        try {
            $userID = $this->auth->id ?? 3;
            $list = SignUp::instance()
                ->field('activity_id as id, user_id, number')
                ->where(['user_id' => $userID])
                ->group('activity_id')
                ->paginate($this->pageSize, false, ['page' => $this->page])->each(function (&$value) use ($userID) {
                    if ($goodsIds = Activity::instance()->where(['id' => $value['id']])->value('goods_ids')) {
                        $goodsIds = explode(',', $goodsIds);
                        $goodsArray = collection(Goods::instance()
                            ->field('id, goods_name, goods_images, goods_desc, type, punch_number, input_params')
                            ->where(['id' => ['in', $goodsIds]])
                            ->select())
                            ->toArray();
                        foreach ($goodsArray as &$item) {
                            /*$item['is_true'] = ($item['punch_number'] <= $value['number']) ? 2 : 1;*/
                            $awardCeremony = AwardCeremony::instance()->get(['activity_id' => $value['id'], 'goods_id' => $item['id'], 'user_id' => $this->auth->id ?? 0]);
                            $item['is_true'] = empty($awardCeremony) ? 1 : 2;
                            if (!empty($item['inputParams'])) {
                                $item['inputParams'] = json_encode($item['input_params']);
                            }
                        }
                        $value['list'] = $goodsArray;
                    }
                });
            $this->success('success', ['totalPage' => $list->lastPage(), 'list' => $list->items()]);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取已领奖的产品
     * @throws
     * */
    public function getReceivedAward()
    {
        $list = AwardCeremony::instance()
            ->with(['activity', 'goods', 'address'])
            ->where(['user_id' => $this->auth->id ?? 0])
            ->paginate($this->pageSize, false, ['page' => $this->page])->each(function (&$value) {
                $value['goods']['input_params'] = json_decode($value['goods']['input_params'], true);
            });
        $this->success('success', $list);
    }

    /**
     * 修改头像
     * @throws
     * */
    public function editAvatar()
    {
        try {
            $params = $this->request->post();
            if (empty($params['avatar'])) {
                throw new Exception('缺少头像');
            }
            $response = (new \app\common\model\User)->editAvatar($params, $this->auth->id ?? 0);
            $this->success('success', $response);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 修改昵称
     * @throws
     * */
    public function editNickname()
    {
        try {
            $params = $this->request->post();
            if (empty($params['nickname'])) {
                throw new Exception('缺少昵称');
            }
            $response = (new \app\common\model\User)->editNickname($params, $this->auth->id ?? 0);
            $this->success('success', $response);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 加入城市组别
     * @throws
     * */
    public function addCityGroup()
    {
        try {
            $params = $this->request->post();
            if (empty($params['city_group_id'])) {
                throw new Exception('缺少组ID');
            }

            if (!Group::instance()->get(['id' => $params['city_group_id']])) {
                throw new Exception('加入组不存在');
            }
            $response = (new \app\common\model\User)->saveCityGroup($params, $this->auth->id ?? 0);
            $this->success('success', $response);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取城市组别
     * @throws
     * */
    public function getCityGroup()
    {
        try {
            $list = collection(Group::instance()->field('id, group_name')->where(['status' => 1])->select())->toArray();
            $this->success('success', $list);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 活动打卡记录
     * @throws
     * */
    public function checkInRecord()
    {
        try {
            $params = $this->request->get();
            if (empty($params['activity_id'])) {
                throw new Exception('缺少活动ID');
            }
            $list = SignUp::instance()
                ->field('id, activity_id, user_id, number, createtime')
                ->where(['activity_id' => $params['activity_id']])
                ->where(['user_id' => $this->auth->id ?? 0])
                ->paginate($this->pageSize, false, ['page' => $this->page]);
            $this->success('success', ['totalPage' => $list->lastPage(), 'list' => $list->items()]);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取活动中的组排名统计
     * @throws
     * */
    public function getGroupRankingCount()
    {
        $params = $this->request->get();
        if (empty($params['activity_id'])) {
            $this->error('缺少活动ID');
        }
        try {
            if (!$activity = Activity::instance()->get(['id' => $params['activity_id']])) {
                throw new Exception('该活动不存在');
            }
            // todo 获取所有用户的打卡数量分组排名
            $rows = collection(SignUp::instance()
                ->alias('t1')
                ->field('sum(t1.number) as number, t2.city_group_id, t3.group_name')
                ->join('user t2', 't1.user_id = t2.id', 'LEFT')
                ->join('group t3', 't2.city_group_id = t3.id', 'LEFT')
                ->where(['t1.activity_id' => $activity['id']])
                ->order('number desc, t1.createtime asc')
                ->group('t2.city_group_id')
                ->select())
                ->toArray();
            $groupRanking = 0;
            foreach ($rows as $key => $value) {
                $city_group_id = $this->auth->city_group_id ?? 0;
                if ($value['city_group_id'] == $city_group_id) {
                    $groupRanking = ($key + 1);
                }
            }
            // todo 获取所有用户的打卡数量
            $myRanking = collection(SignUp::instance()
                ->alias('t1')
                ->field('t1.user_id, sum(t1.number) as number, t2.city_group_id, t3.group_name')
                ->join('user t2', 't1.user_id = t2.id', 'LEFT')
                ->join('group t3', 't2.city_group_id = t3.id', 'LEFT')
                ->where(['t1.activity_id' => $activity['id']])
                ->order('number desc, t1.createtime asc')
                ->group('t1.user_id')
                ->select())
                ->toArray();
            $nationwideRanking = 0;
            foreach ($myRanking as $key_ => $value_) {
                $user_id = $this->auth->id ?? 0;
                if ($value_['user_id'] == $user_id) {
                    $nationwideRanking = ($key_ + 1);
                }
            }
            $userGroup = (new \app\admin\model\User())->field('id, city_group_id')->with(['cityUserGroup'])->where(['id' => $this->auth->id ?? 0])->find();
            $row['groupName'] = empty($userGroup['group_name']) ? '' : $userGroup['group_name'];
            $row['groupRanking'] = $groupRanking; // todo 我的组排名
            $row['nationwideRanking'] = $nationwideRanking; // todo 我的全国排名
            $row['MyCountPunchNumber'] = SignUp::instance()->where([
                'user_id' => $this->auth->id ?? 0
            ])->sum('number'); // todo 我的累计打卡
            $this->success('success', $row);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取活动中的组排名(光荣榜)
     * @throws
     * */
    public function getGroupRanking()
    {
        try {
            $params = $this->request->get();
            if (empty($params['activity_id'])) {
                throw new Exception('缺少活动ID');
            }
            // 获取活动
            if (!$rows = Activity::instance()->where(['id' => $params['activity_id']])->find()) {
                throw new Exception('活动不存在');
            }
            $list = SignUp::instance()
                ->field('user_id, sum(number) as number')
                ->with(['userHasOne'])
                ->where(['activity_id' => $params['activity_id']])
                ->order('number desc, createtime asc')
                ->group('user_id')
                ->limit($rows['ranking_number'])
                ->paginate($this->pageSize, false, ['page' => $this->page])->each(function (&$value) {
                    $cityGroupId = (new \app\common\model\User())->where(['id' => $value['user_id']])->value('city_group_id');
                    $value['GroupName'] = Group::instance()->where(['id' => $cityGroupId])->value('group_name');
                });
            $this->success('success', ['totalPage' => $list->lastPage(), 'list' => $list->items()]);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 回显领取奖品的文本信息
     * */
    public function showText()
    {
        $params = $this->request->get();
        if (empty($params['activity_id'])) {
            $this->error('缺少活动ID');
        }
        if (empty($params['goods_id'])) {
            $this->error('缺少商品ID');
        }
        $result = AwardCeremony::get(['activity_id' => $params['activity_id'], 'goods_id' => $params['goods_id'], 'user_id' => $this->auth->id ?? 0]);
        $this->success('success', $result);
    }

    /**
     * 修改回显领取奖品的文本信息
     * */
    public function updateShowText()
    {
        $params = $this->request->post();
        if (empty($params['id'])) {
            $this->error('缺少回显参数');
        }
        if (empty($params['content'])) {
            $this->error('缺少内容');
        }
        if (!$result = AwardCeremony::get(['id' => $params['id'], 'user_id' => $this->auth->id ?? 0])) {
            $this->error('未找到该商品下的详情文本');
        }
        Db::startTrans();
        try {
            $result->allowField(true)->save([
                'content' => htmlspecialchars_decode($params['content'])
            ]);
            CountNumber::instance()->allowField(true)->save([
                'type_id' => $params['id'],
                'type' => 1,
                'user_id' => $this->auth->id ?? 0
            ]);
            Db::commit();
            $this->success('修改成功');
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
    }
}
